package com.yuzhi.master.drainWn.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuzhi.common.core.page.PageDataInfo;
import com.yuzhi.common.util.StringUtils;
import com.yuzhi.master.drainWn.mapper.DrainSludgeMapper;
import com.yuzhi.master.drainWn.mapper.DrainWnMapper;
import com.yuzhi.master.drainWn.service.DrainSludgeService;
import com.yuzhi.master.drainWn.vo.*;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class DrainSludgeServiceImpl implements DrainSludgeService {

    private final DrainSludgeMapper drainSludgeMapper;
    private final DrainWnMapper drainWnMapper;

    @Override
    public List<SludgeOutputVO> getLast12MonthsSludgeOutput(String factId) {
        // 1. 计算时间范围（过去12个月）
        LocalDate now = LocalDate.now();
        LocalDate startDate = now.minusMonths(11).withDayOfMonth(1); // 12个月前（包含当前月）
        LocalDate endDate = now.withDayOfMonth(now.lengthOfMonth()); // 当前月最后一天

        // 2. 查询数据库
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        List<SludgeOutputVO> dbResults = drainSludgeMapper.getLast12MonthsSludgeOutput(
                startDate.format(formatter),
                endDate.format(formatter),
                factId  // 传递污水厂ID
        );

        // 3. 转换为Map便于查找
        Map<String, Double> resultMap = dbResults.stream()
                .collect(Collectors.toMap(SludgeOutputVO::getMonth, SludgeOutputVO::getTotalSludge));

        // 4. 生成完整的12个月数据（确保每个月都有数据）
        List<SludgeOutputVO> fullResults = new ArrayList<>();
        YearMonth current = YearMonth.from(startDate);

        for (int i = 0; i < 12; i++) {
            String monthKey = current.format(DateTimeFormatter.ofPattern("yyyy-MM"));
            Double total = resultMap.getOrDefault(monthKey, 0.0);

            SludgeOutputVO vo = new SludgeOutputVO();
            vo.setMonth(monthKey);
            vo.setTotalSludge(total);

            fullResults.add(vo);
            current = current.plusMonths(1);
        }

        return fullResults;
    }

    /**
     * 分页查询污泥信息列表
     */
    @Override
    public PageDataInfo<DrainWn> selectWnPageList(DrainWnReq req)
    {
        LambdaQueryWrapper<DrainWn> lqw = new LambdaQueryWrapper<DrainWn>();
        lqw.like(StringUtils.isNotBlank(req.getCph()), DrainWn::getCph, req.getCph());
        lqw.like(StringUtils.isNotBlank(req.getWeigher()), DrainWn::getWeigher, req.getWeigher());
        lqw.like(StringUtils.isNotBlank(req.getReceivingUnit()), DrainWn::getReceivingUnit, req.getReceivingUnit());
        lqw.orderByDesc(DrainWn::getCreateTime);
        Page<DrainWn> page = drainWnMapper.selectPage(req.getPageQuery().build(), lqw);

        return PageDataInfo.build(page);
    }

    /**
     * 查询污泥运输数据
     */
    @Override
    public DrainWnVo queryById(String id){
        return drainWnMapper.selectVoById(id);
    }


    /**
     * 批量删除污泥数据
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            // 业务校验逻辑
        }
        return drainWnMapper.deleteBatchIds(ids) > 0;
    }


    /**
     * 新增淤泥运输
     */
    @Override
    public Boolean insertByBo(DrainWnBo bo)
    {
        DrainWn add = BeanUtil.toBean(bo, DrainWn.class);

        boolean flag = drainWnMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改淤泥运输量
     * @param bo
     * @return
     */
    @Override
    public Boolean updateByBo(DrainWnBo bo)
    {
        DrainWn update = BeanUtil.toBean(bo, DrainWn.class);

        return drainWnMapper.updateById(update) > 0;
    }




}
